<template>
  <BasicModal v-bind="$attrs" @register="registerModal"
              :width="800"
              :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm"/>
  </BasicModal>
</template>

<script setup lang="ts">
import {computed, ref, unref} from 'vue';
import {formSchema} from './terminal.data';
import {useMessage} from '@/hooks/web/useMessage';
import {getTerminalApi, addTerminalApi, editTerminalApi} from '@/api/core/terminal.api';
import {BasicModal, useModalInner} from '@/components/Modal';
import {BasicForm, useForm} from '@/components/Form';
import {listTerminalModelApi} from "@/api/core/terminalModel.api";

const emit = defineEmits(['success', 'register']);
const {createMessage} = useMessage();
const isUpdate = ref(true);

const [registerForm, {updateSchema, resetFields, setFieldsValue, validate}] = useForm({
  labelWidth: 80,
  schemas: formSchema,
  showActionButtonGroup: false,
});

const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
  resetFields();
  setModalProps({confirmLoading: false});
  isUpdate.value = !!data?.isUpdate;

  if (unref(isUpdate)) {
    const terminal = await getTerminalApi(data.record.id);
    setFieldsValue({...terminal});

    let modelsOptions = await listTerminalModelApi({brandId: terminal.brandId});
    updateSchema({
      field: 'modelId',
      componentProps: {
        options: modelsOptions.items,
        optionFilterProp: 'modelName',
        fieldNames: {
          label: 'modelName',
          key: 'id',
          value: 'id',
        },
      },
    });


  }
});

/** 标题初始化 */
const getTitle = computed(() => (!unref(isUpdate) ? '新增终端信息' : '编辑终端信息'));

/** 提交按钮 */
async function handleSubmit() {
  try {
    const values = await validate();
    setModalProps({confirmLoading: true});
    unref(isUpdate)
      ? await editTerminalApi(values).then(() => {
        closeModal();
        createMessage.success('编辑终端信息成功！');
      })
      : await addTerminalApi(values).then(() => {
        closeModal();
        createMessage.success('新增终端信息成功！');
      });
    emit('success');
  } finally {
    setModalProps({confirmLoading: false});
  }
}
</script>
